package com.onelap.bls.tc.activity.entry;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.bls.blslib.eventbus.EventBusUtils;
import com.google.gson.Gson;
import com.onelap.bls.tc.R;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothDialogHelper;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeParams;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeService;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeUtil;
import com.onelap.bls.tc.activity.calibration.CalibrationActivity;
import com.onelap.bls.tc.activity.index.DeviceBean;
import com.onelap.bls.tc.activity.index.IndexActivity;
import com.onelap.bls.tc.utils.BLeUtil;
import com.onelap.bls.tc.utils.TitleBar;

import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeParams.ServiceParams.EXTRA_DATA;
import static com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Get_Data;


public class EntryActivity extends BaseActivity implements BluetoothLeUtil.BluetoothUtilCallback {

    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_electric)
    TextView tvElectric;
    @BindView(R.id.btn_wheel_diameters)
    Button btnWheelDiameters;
    @BindView(R.id.btn_slope)
    Button btnSlope;
    @BindView(R.id.btn_switch_to_ble)
    Button btnSwitchToBle;
    private DeviceBean deviceBean;
    private BluetoothLeUtil bluetoothLeUtil;
    private BluetoothAdapter bluetoothAdapter;

    private ProgressDialog progressDialog;

    private boolean isConnectDevice = false;  //连接到蓝牙设备
    //private Timer timer;

    private int TIME = 2000;  //每隔1s执行一次.

    Handler handler = new Handler();

    private Handler handler2;


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                handler.postDelayed(this, TIME);
                bluetoothLeUtil.displayVersionBattery();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void initParams() {
        super.initParams();

        deviceBean = new Gson().fromJson(getIntent().getStringExtra("DeviceBean"), DeviceBean.class);
        bluetoothLeUtil = new BluetoothLeUtil(this);

        bluetoothAdapter = bluetoothLeUtil.getBluetoothAdapter(getActivity());

        if (bluetoothAdapter == null) {
            BluetoothDialogHelper.showDialog(getActivity(), "提示", "当前设备不支持蓝牙", false, new BluetoothDialogHelper.DialogBtnCallback() {
                @Override
                public void dialogBtnCallback(int type) {
                    AppUtils.exitApp();
                }
            });
            return;
        }

        bluetoothLeUtil.bindBluetoothService(getActivity(), BluetoothLeService.class, BluetoothLeParams.intentActions);
        //timer = new Timer();
        handler2 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        tvElectric.setText("剩余电量： ".concat(String.valueOf(msg.obj)).concat("%"));
                        break;
                    case 1:
                        tvVersion.setText("固件版本： ".concat(String.valueOf(msg.obj)));
                        break;
                    case 10:
                        new AlertDialog.Builder(getActivity()).setTitle("警告").setMessage("设备蓝牙已经断开连接!!!").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ActivityUtils.startActivity(getActivity(), IndexActivity.class);
                                getActivity().finish();
                            }
                        }).show();
                        break;
                }
            }
        };
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_entry;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle("校准选择");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
        titleBar.setLeftImageResource(R.mipmap.a2);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothLeUtil.closeBleConnectDevice();
                getActivity().finish();
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
        super.initView();
        tvId.setText("设备ID：".concat(deviceBean.getDevice().getName()));

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("连接中，请稍等......");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @OnClick(R.id.btn_wheel_diameters)
    public void onBtnWheelDiametersClicked() {
        //timer.cancel();
        handler.removeCallbacks(runnable);
        Intent intent = new Intent();
        intent.putExtra("CalibrationType", "ONE");
        intent.putExtra("DeviceBean", new Gson().toJson(deviceBean));
        intent.setClass(getActivity(), CalibrationActivity.class);
        getActivity().startActivity(intent);
    }

    @OnClick(R.id.btn_slope)
    public void onBtnSlopeClicked() {
        //timer.cancel();
        handler.removeCallbacks(runnable);
        Intent intent = new Intent();
        intent.putExtra("CalibrationType", "TWO");
        intent.putExtra("DeviceBean", new Gson().toJson(deviceBean));
        intent.setClass(getActivity(), CalibrationActivity.class);
        getActivity().startActivity(intent);
    }

    @Override
    protected void initResume() {
        super.initResume();
        handler.postDelayed(runnable, TIME);
    }

    @OnClick(R.id.btn_switch_to_ble)
    public void onBtnSwitchToBleClicked() {
        if (!isConnectDevice) {
            ToastUtils.showShort("设备未连接");
            return;
        }
        new MaterialDialog.Builder(this).title("提示：").content("切换至蓝牙模式后将无法再次连接，确认切换么？")
                .positiveText("确定").negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        try {
                            bluetoothLeUtil.writeRXCharacteristicUTF_8("FFFF");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @Override
    public void onBluetoothUtilCallback(String utilCallbackStatue, BluetoothGatt gatt, BluetoothDevice device, int rssi, byte[] scanRecord, IBinder rawBinder, final Intent intent) {
        switch (utilCallbackStatue) {
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_ServiceConnected:
                BluetoothLeService bluetoothLeService = ((BluetoothLeService.LocalBinder) rawBinder).getService(bluetoothLeUtil, bluetoothAdapter);
                bluetoothLeUtil.openBleConnectDevice(bluetoothLeService, deviceBean.getDevice());
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_ServiceDisconnected:
                ToastUtils.showLong("服务失去连接");
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connecting:
                progressDialog.show();
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connected:
                isConnectDevice = true;
                if (progressDialog.isShowing()) progressDialog.dismiss();
                handler.postDelayed(runnable, TIME);
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_DisConnecting:
                isConnectDevice = false;
                if (progressDialog.isShowing()) progressDialog.dismiss();
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_DisConnected:
                isConnectDevice = false;
                if (progressDialog.isShowing()) progressDialog.dismiss();
                LogUtils.i("111111111111111111111111");
                tempSendMessage(10, "");
                /*new AlertDialog.Builder(getActivity()).setTitle("警告").setMessage("设备蓝牙已经断开连接!!!").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityUtils.startActivity(getActivity(), IndexActivity.class);
                        getActivity().finish();
                    }
                }).show();*/
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connect_Fail:
                ToastUtils.showShort("当前设备不能连接");
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Discovered:

                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Discovered_Fail:
                LogUtils.i("STATUS_BluetoothDevice_Discovered_Fail");
                break;
            case STATUS_BluetoothDevice_Get_Data:
                byte[] txValue = intent.getByteArrayExtra(EXTRA_DATA);
                String text = null;
                try {
                    text = new String(txValue, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (text != null && text.equals("FFFF")) {
                    EventBusUtils.sendStickyEvent(new Event(0));
                    bluetoothLeUtil.closeBleConnectDevice();
                    getActivity().finish();
                }
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Get_BatteryData:
                byte[] txValue2 = intent.getByteArrayExtra(EXTRA_DATA);
                final StringBuilder text2 = new StringBuilder();
                for (byte b : txValue2) {
                    String a = String.valueOf(b);
                    text2.append(a);
                }
                Message message = new Message();
                message.what = 0;
                message.obj = text2;
                handler2.sendMessage(message);
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Get_VersionData:
                byte[] txValue3 = intent.getByteArrayExtra(BLeUtil.Params.EXTRA_DATA);
                String text3 = "";
                try {
                    text3 = new String(txValue3, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                tempSendMessage(1, text3);
                break;
        }
    }

    private void tempSendMessage(int what, String message) {
        Message message1 = new Message();
        message1.what = what;
        message1.obj = message;
        handler2.sendMessage(message1);
    }


    @Override
    protected void initOnDestroy() {
        bluetoothLeUtil.closeBleConnectDevice();
        handler.removeCallbacks(runnable);
        super.initOnDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        getActivity().finish();
    }

    // Handler handler2 = new Handler();
}
